165B - Burning Midnight Oil - CodeForces Solution


binary search implementation *1500

Please click on ads to support us..

Python Code:

def calc(num, k):
    sum = 0
    i = 0
    while k**i <= num:
        sum += int(num/ k**i)
                i+=1
    return sum


def Binary(sum, k):
    l = 0
    r = 10**9
    while l<r:
        mid = int(l +(r - l)/2)
        ans = calc(mid, k)
        if ans < sum:
            l = mid + 1
        else:
            r = mid
    return l



list=[int(item) for item in input().split()]
sum = list[0]
k = list[1]
print(Binary(sum, k))

C++ Code:

#include<iostream>

using namespace std;

typedef long long int ll;
const int N = 100000000000;

int main()
{
	ll n, m, x, k;
	ll high, low, mid, ans, cnt;

    cin >> n >> k;

	high = n; low = 1; ans = N;
	while (low <= high)
	{
		mid = (high + low) / 2;

		cnt = mid;
        m = k;
		while (true)
		{
			x = mid / m; m *= k;
			cnt += x;

			if (!x) break;
        }

		if (cnt == n) {
			ans = mid;
			break;
		}

		if (cnt > n) ans = min(ans, mid), high = mid - 1;
		else low = mid + 1;
	}
    cout << ans << "\n";
	return 0;
}

		 	  		 		  			    	 			  			


Comments

Submit
0 Comments
More Questions

1627B - Not Sitting
1663C - Pōja Verdon
1497A - Meximization
1633B - Minority
688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays
540A - Combination Lock
1553C - Penalty
1474E - What Is It
1335B - Construct the String
1004B - Sonya and Exhibition
1397A - Juggling Letters
985C - Liebig's Barrels
115A - Party
746B - Decoding
1424G - Years
1663A - Who Tested
1073B - Vasya and Books
195B - After Training
455A - Boredom
1099A - Snowball
1651D - Nearest Excluded Points
599A - Patrick and Shopping
237A - Free Cash
1615B - And It's Non-Zero
1619E - MEX and Increments
34B - Sale
1436A - Reorder
1363C - Game On Leaves